﻿using System;
using BusinessBingo.CommandHandlers.Base;
using BusinessBingo.CommandHandlers.Interfaces;
using BusinessBingo.CommandHandlers.Results;
using BusinessBingo.Commands;
using BusinessBingo.Data.Interfaces;
using BusinessBingo.Model;
using BusinessBingo.Model.Interfaces;

namespace BusinessBingo.CommandHandlers
{
    public class CreateUserCommandHandler :
        BaseCommandHandler,
        ICreateUserCommandHandler
    {
        private IUserRepository _userRepository;

        public CreateUserCommandHandler(
            IUserRepository userRepository,
            IValidationState validationState,
            IUnitOfWork unitOfWork)
            : base(validationState, unitOfWork)
        {
            this._userRepository = userRepository;
        }

        public CreateUserCommandHandlerResult Execute(CreateUserCommand createUserCommand)
        {
            CreateUserCommandHandlerResult result = new CreateUserCommandHandlerResult();

            if(createUserCommand == default(CreateUserCommand))
                throw new ArgumentNullException("CreateUserCommand");

            if (string.IsNullOrWhiteSpace(createUserCommand.UserName) == true)
                this._validationState.AddError<CreateUserCommand>(x => x.UserName, ErrorTypes.Empty);

            if (createUserCommand.GroupId == default(Guid))
                this._validationState.AddError<CreateUserCommand>(x => x.GroupId, ErrorTypes.Empty);

            if (this._validationState.IsValid == false)
                return result;

            User user = new User();
            user.Name = createUserCommand.UserName;
            user.GroupId = createUserCommand.GroupId;

            user = this._userRepository.AddItem(user);

            base.Complete();

            result.Succeeded = true;
            result.User = user;

            return result;
        }
    }
}